<template>
  <GridView v-if="gridJson" :gridJson="gridJson">
    <!-- 查询列表扩展 -->
    <template #query> </template>
    <!-- 数据处理扩展,存在时替换默认处理逻辑,插入对应字段名称的插槽即可替换默认内容渲染 -->
    <template #webApi="{ scope, field }">
      <div>{{ handleWebApi(scope.row.source) }}</div>
    </template>
    <template #serviceApi="{ scope, field }">
      <div>
        {{ scope.row.type === 'enum' ? '' : '/' + toProperCase(scope.row.source, '_') + 'Api' }}
      </div>
    </template>
    <!-- 操作列表扩展 -->
    <template #operate="{ scope }">
      <el-button
          v-if="scope.row.type === 'table' || scope.row.type === 'view'"
          style="order: 6"
          size="small"
          type="primary"
          @click="codePreview(scope.row)"
      >预览源码</el-button
      ></template
    >
    <!-- 编辑页面扩展任意属性 -->
    <template #EDIT_ADD_FIELD="{ modal }">
      <el-form-item v-if="modal.type === 'enum'" label="枚举设置 label:value:type(tag类型)">
        <el-select
            v-model="editEnum[modal.id]"
            placeholder="label:value 必填"
            size="small"
            filterable
            allow-create
            default-first-option
            @change="addEditEnum($event, modal)"
            @focus="loadOptions(modal)"
            style="width: 240px"
        >
          <el-option
              v-for="(item, index) in editEnums[modal.source]"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="true"
          ><span style="float: left"
          >{{ item.label }} : {{ item.value }}
              <span v-if="item.type"> : {{ item.type }}</span></span
          >
            <span
                style="
                float: right;
                color: var(--el-text-color-secondary);
                font-size: 13px;
                cursor: pointer;
              "
                @click="delEnum(item, modal)"
            >
              <el-icon><Close /></el-icon>
            </span>
            <el-tag v-if="item.type" :type="item.type">{{ item.label }}</el-tag></el-option
          >
        </el-select>
        <el-button size="small" type="primary" style="margin-left: 10px" @click="addOption(modal)"
        >添加到选项</el-button
        >
      </el-form-item>
    </template>
    <!-- 添加页面扩展任意属性 -->
    <template #ADD_ADD_FIELD="{ modal }"> </template>
  </GridView>
  <el-empty description="网格数据加载中" v-else />
  <CodePreView
      v-if="openCodePreView"
      v-model:isOpen="openCodePreView"
      :genId="genId"
      @editOk="codePreviewOk"
  />
</template>
<script setup>
import GridView from '../grid/json/preview/GridView.vue'
import CodePreView from './CodePreView.vue'
import { toProperCase } from '@/utils/str'
import { ElMessage } from 'element-plus'
// 单页面网格模版
import { ref, inject, onBeforeMount } from 'vue'
import { useRoute } from 'vue-router'
const router = useRoute()
const api = inject('api')
const gridJson = ref(null)
const enumApi = api.getApi('FaSysEnum', '150fa1064f75f0922399cb3e9bcd169c')
const optionApi = api.getApi('FaSysOption', '458cc45451c0dee57a1a9a9dae4ce3e2')
const openCodePreView = ref(false)
const genId = ref()
const editEnum = ref({})
const editEnums = ref({})

onBeforeMount(() => {
  api
      .getApi('FaSysGrid', router.meta.grids[0])
      .getCurrentJson()
      .then((data) => {
        gridJson.value = data
      })
})
// 判断使用webApi
function handleWebApi(webApi) {
  const apiObj = api.getApi(toProperCase(webApi, '_'))
  return apiObj.constructor.name
}

// 预览源码
function codePreview(row) {
  genId.value = row.genId
  openCodePreView.value = true
}

// 加载选项
function loadOptions(modal) {
  enumApi.getByCode(modal.source).then((ref) => {
    try {
      editEnums.value[modal.source] = JSON.parse(ref.data.dataJson)
    } catch (e) {
      console.warn(`未创建该枚举 ${modal.source}`)
    }
  })
}
// 添加编辑枚举
function addEditEnum(value, modal) {
  // 判断格式
  let keyValueArr = value.split(':')
  if (keyValueArr.length === 1) {
    keyValueArr.push(keyValueArr[0])
  }
  if (!editEnums.value[modal.source]) {
    editEnums.value[modal.source] = []
  }
  // 判断是否重复
  for (const item of editEnums.value[modal.source]) {
    if (item.value === keyValueArr[1]) {
      item.label = keyValueArr[0]
      item.type = keyValueArr[2]
    }
  }

  // let queryEnum = editEnums.value[modal.source].filter((item) => item.value === keyValueArr[1])
  // if (queryEnum.length > 0) {
  //   ElMessage.warning(`添加枚举重复 ${JSON.stringify(queryEnum[0])}`)
  //   return
  // }
  let enumItem = {
    label: keyValueArr[0],
    value: keyValueArr[1]
  }
  if (keyValueArr[2]) {
    enumItem.type = keyValueArr[2]
  }
  editEnums.value[modal.source].push(enumItem)
  // 提交服务器
  enumApi.addEnumItem(enumItem, modal.source, modal.name)
}
// 删除枚举
function delEnum(item, modal) {
  editEnums.value[modal.source] = editEnums.value[modal.source].filter(
      (itemEnum) => itemEnum !== item
  )
  enumApi.delEnumItem(item, modal.source)
}
// 添加枚举数据源到选项
function addOption(modal) {
  optionApi
      .add({
        name: modal.name,
        dataSourceId: modal.id,
        keyField: 'label',
        valueField: 'value',
        tree: 0
      })
      .then((res) => {
        ElMessage({ message: '添加成功', type: 'success' })
      })
}
// 关闭弹窗
function codePreviewOk() {
  openCodePreView.value = false
}
</script>
<style scoped></style>
